import axios from 'axios';
import React, { Component } from 'react';
import PubSub from 'pubsub-js';

import SearchCss from './index.module.css';


export default class Search extends Component {
  deliverSearch = async () => {
    // 刚点击时，子组件发布一次，传递若干状态
    PubSub.publish('updateUsers', {
      isFirstOpen: false,
      isLoading: true
    })
    let inputVal = this.input.value;
    try {
      const { items: res } = await (await axios.get(`https://api.github.com/search/users?q=${inputVal.trim()}`)).data;
      // 得到数据时，子组件发布一次，传递若干状态
      PubSub.publish('updateUsers', {
        isFirstOpen: false,
        isLoading: false,
        users: res
      });
    } catch (e) {
      // 遇到错误时，子组件发布一次，传递若干状态
      PubSub.publish('updateUsers', {
        errMessage: e.message
      });
    }

  }
  render() {
    return (
      <div className={SearchCss.container}>
        <h2>github搜索案例</h2>
        <div className={SearchCss.searcharea}>
          <input type="text" ref={c => this.input = c} /> &nbsp;
          <button onClick={this.deliverSearch}>搜索</button>
        </div>
      </div>
    )
  }
}
